export const apiCore = (url, options) => {
  const config = useRuntimeConfig();
  const nuxtApp = useNuxtApp();
  return useFetch(url, {
    ...options,
    baseURL: config.public.baseURL,
    //请求拦截器
    onRequest({ options }) {
      let token = useUserStore().getToken();
      options.headers = {
        ...options.headers,
        Authorization: "Bearer " + token,
      };
    },
    //ok为false时两个都会执行 http状态码为200，500，404等
    //响应拦截 2xx以内
    onResponse({ response }) {
      if (response.ok) {
        if (response._data.code !== 200) {
          if (import.meta.client) {
            ElMessage.error(response._data.code + ":" + response._data.message);
          } else {
            nuxtApp.runWithContext(() => {
              navigateTo({
                path: "/myError",
                query: {
                  code: response._data.code,
                  message: response._data.message,
                },
              });
            });
          }
        }
      }
    },
    //响应拦截 2xx以外
    onResponseError({ response }) {
      if (import.meta.client) {
        ElMessage.error(response._data.code + ":" + response._data.message);
      } else {
        nuxtApp.runWithContext(() => {
          navigateTo({
            path: "/myError",
            query: {
              code: response._data.code,
              message: response._data.message,
            },
          });
        });
      }
    },
  });
};
export const GetAPi = (url, options) => {
  return new Promise((resolve, reject) => {
    apiCore(url, {
      ...options,
      method: "GET",
    })
      .then((res) => {
        resolve(res.data.value);
      })
      .catch((err) => {
        reject(err);
      });
  });
};
